from flask_login import current_user
from exlib.restviewset.reqparse import RequestParser
from exlib.restplus.resource import ListResource, SingleResource
from app.user.models import Permission
from app.user.serializers.permission import PermissionSerializer
from app import api_base as api
from app.perms import USER_PERMISSION, VIEW, ADD, EDIT, DELETE
from utils.decorators import marshal_item, marshal_table
from utils.perm import perm_required
from utils import pagination, get_pagination_arguments, get_object_or_404


# from utils import current_company


class PermissionView(SingleResource):
    model_class = Permission
    model_serializer = PermissionSerializer

    @perm_required(USER_PERMISSION, VIEW)
    @marshal_item(PermissionSerializer)
    def get(self, id):
        obj = get_object_or_404(self.model_class, id=id)
        return PermissionSerializer(obj).item()

    poster = RequestParser()
    poster.add_argument('name', type=str, required=False, store_missing=False, help='权限名')
    poster.add_argument('desc', type=str, required=False, store_missing=False, help='补充说明')

    @perm_required(USER_PERMISSION, EDIT)
    @api.expect(poster)
    @marshal_item(PermissionSerializer)
    def put(self, id):
        obj = get_object_or_404(self.model_class, id=id)
        args = self.poster.parse_args()
        if args:
            obj.modify(**args)
            obj.save()
        return PermissionSerializer(obj).item(
            message=self.msg_edit_success
        )


class PermissionsView(ListResource):
    model_class = Permission
    model_serializer = PermissionSerializer

    filter = RequestParser()
    filter.add_argument('id', dest='id', type=str, required=False, store_missing=False, help='user id')

    @perm_required(USER_PERMISSION, VIEW)
    @api.expect(pagination, filter)
    @marshal_table(PermissionSerializer)
    def get(self):
        args = self.filter.parse_args()
        modules = current_user._company_.modules
        condition = {k: args.k for k in args}
        condition['module__in'] = modules
        objs = Permission.objects.filter(**condition)
        pargs = pagination.parse_args()
        res = self.order_paginate(objs, pargs)
        return PermissionSerializer(res).table(
            total=objs.count(),
            pargs=pargs
        )

    poster = RequestParser()
    poster.add_argument('content', type=str, required=True, help='权限目标')
    poster.add_argument('action', type=str, required=True, help='操作行为')
    poster.add_argument('name', type=str, required=False, store_missing=False, help='权限名')
    poster.add_argument('desc', type=str, required=False, store_missing=False, help='补充说明')

    @perm_required(USER_PERMISSION, ADD)
    @marshal_item(PermissionSerializer)
    def post(self):
        args = self.filter.parse_args()
        obj = self.model_class(**args)
        obj.save()
        return PermissionSerializer(obj).item(
            message=self.msg_add_success
        )
